<?php
/**
 * Users controller class
 *
 */
class CategoriesController extends Admin_Controller
{
	private $table_privilege;
	private $table_tags;
    private $_tree;

	public function init()
    {
	    $this->tree = &$this->_menu;
    	$this->_table = &$this->table_categories;
    	$this->_table_field = 'id_cat';

        parent::init();
        $this->setActiveCat(89);

        $this->table_tags = new Admin_Table_Tags();
    }

    /**
     * index action method
     *
     */
    public function indexAction()
    {
    	$this->page_type = 'list';

    	$lclm = new Llib_List($this->_request, $this->_sess);
    	$lclm->AddColumn('Название', 'menu_name_ru', array('width' => '90%'));

    	//$lclm->AddFunc(array('title' => 'Топ', 'name' => 'top', 'field' => 'is_top'));
    	$lclm->AddFunc(array('title' => 'Показать', 'name' => 'show', 'field' => 'is_show'));
    	$lclm->AddFunc();
    	$lclm->AddFunc(array('name' => 'add', 'type' => 'button'));
    	$lclm->AddFunc(array('name' => 'move', 'type' => 'button', 'img' => 'folder_go.png'));
    	$lclm->AddFunc(array('name' => 'remove', 'type' => 'button', 'img' => 'folder_delete.png', 'ajax' => 'list_func_cat_remove'));

    	//$lclm->AddFuctions(array('folder_add', 'active', 'folder_edit', 'folder_move', 'folder_remove'));

    	$lclm->AddData($this->_table->GetDataList());

    	$data = array();
    	if($this->_request->isPost())
    	{
	    	$data['id_cat_view'] = $this->_request->getParam('id_cat_view', 62);
    	}

    	$params = $this->SessionVars($data, array('id_cat_view'), '');
    	if(!(intval($params['id_cat_view']) > 0)) $params['id_cat_view'] = 62;
		if($this->_user->role_id != 1) $params['id_cat_view'] = 62;


        $this->startContent();
	        $this->view->xmlWriter->startElement("Main");
	        $this->view->xmlWriter->writeAttribute('id_cat_view', $params['id_cat_view']);
	        $this->view->assign('List', $lclm->GetList());
		    $this->view->xmlWriter->endElement();
	    $this->view->xmlWriter->endElement();
    }

    public function addAction()
    {
    	$id = $this->_request->getParam('id');
    	$saveexit = $this->_getParam('saveexit');
    	if(!($id > 0)) $this->_redirect('/error/e404');

 		$element = $this->tree->pickNode($id, true);
 		$parents = $this->tree->getParents($id);

 		$path = array();
 		$new_url = '';
 		if (sizeof($parents)) {
 			foreach($parents as $parent) {
					$path[] = $parent->menu_name_ru;
					if($parent->idt != '' && $parent->level > 2) $new_url .= '/'.$parent->idt;
 			}
 		}
 		$path[] = $element['menu_name_ru'];

    	$form = new Llib_Form($this->_request);
    	$data = array();

    	$data['id_menu'] = $element['id_menu'];
    	$data['id_type'] = $element['id_type'];
    	$data['controller'] = $element['controller'];

        if ($this->_request->isPost()) {
        	$form->SetSuccess();
        	$data = $form->GetPostedData();
			$type = $data['type'];
			unset($data['type']);

			$data['add_date'] = time();
			$data['modify_date'] = time();

			$data['title_ru'] = $data['menu_name_ru'];
			$data['title_ua'] = $data['menu_name_ua'];
			$data['title_en'] = $data['menu_name_en'];

			$data['idt'] = $this->tstring($data['menu_name_ru']);

			$data['url'] = $new_url.'/'.$data['idt'];
			$data['site'] = $element['site'];


			switch($type)
			{
				case NESE_MOVE_AFTER:
					$new_id = $this->tree->createRightNode($id,$data);
					break;
				case NESE_MOVE_BEFORE:
					$new_id = $this->tree->createLeftNode($id,$data);
					break;
				case NESE_MOVE_BELOW:
					$parent = $this->tree->pickNode($id);
					$data['url'] = $new_url.'/'.$parent->idt.'/'.$data['idt'];
					$new_id = $this->tree->createSubNode($parent->id,$data);
					break;
			}

			 if(is_null($saveexit))  $this->_redirect('/'.$this->controller.'/'.$new_id);
			 else $this->_redirect('/'.$this->controller.'#'.$new_id);
        }

        $data['id_type'] = $this->table_categories->GetTypesList(@$data['id_type']);
        $data['id_menu'] = $this->table_categories->GetMenusList(@$data['id_menu']);
        $data['type'] = $this->GetTypeList(@$data['type'], $path);
        $form->AddData($data);

    	$this->startContent();
	        $this->view->xmlWriter->startElement("Main");
	        $this->view->xmlWriter->writeAttribute('id', $id);
	        $this->view->assign($form->GetFrom());
		    $this->view->xmlWriter->endElement();
	    $this->view->xmlWriter->endElement();
    }

    public function editAction()
    {
    	$id = $this->_request->getParam('id');
    	$saveexit = $this->_getParam('saveexit');
    	if(!($id > 0)) $this->_redirect('/error/e404');

    	$form = new Llib_Form($this->_request);

        if ($this->_request->isPost())
        {
			$d = $form->GetPostedData(array('tags'));
			$tags = $this->_request->getParam('tags');
			//$this->table_tags->insertStr($tags, $this->controller, $id, $this->_user->id);

			//$this->LoadAvatar($id, $form, $d);

        	if($this->_table->update($d, $id)) $form->SetSuccess();
        	else $form->SetError($this->_table->GetError());

			if(!is_null($saveexit))  $this->_redirect('/'.$this->controller.'#'.$id);
        }

        $data = $this->_table->GetDataRow($id);
        $data['id_role'] = $this->table_rules->GetRoleList($id);
        $data['id_type'] = $this->table_categories->GetTypesList(@$data['id_type']);
        $data['id_menu'] = $this->table_categories->GetMenusList(@$data['id_menu']);
        //$data['tags'] = $this->table_tags->GetTagsStringByObjId($this->controller, $id);
        //$data['tags_vals'] = $this->table_tags->GetTagsByObjId($this->controller, $id);

        $form->AddData($data);

    	$this->startContent();
	        $this->view->xmlWriter->startElement("Main");
	        $this->view->xmlWriter->writeAttribute('id', $id);
	        $this->view->assign('Privilege', $this->table_accounts->GetPrivilegeList($id));
	        $this->view->assign($form->GetFrom());
	        $this->view->assign('photos', $this->table_objects->GetDataParamsList(array('id_cat' => $id)));
		    $this->view->xmlWriter->endElement();
	    $this->view->xmlWriter->endElement();
    }

    public function removeAction()
    {
    	$id = $this->_request->getParam('id');
    	if(!($id > 0)) $this->_redirect('/error/e404');

    	$this->tree->deleteNode($id);
    	die('OK');
    	//$this->_redirect('/'.$this->controller);
    }


    public function moveAction()
    {
    	$id = $this->_request->getParam('id');
    	if(!($id > 0)) $this->_redirect('/error/e404');

		$element = $this->tree->pickNode($id, true);
		$parents = $this->tree->getParents($id);
 		$path = array();
 		if (sizeof($parents)) {
 			foreach($parents as $parent) {
					$path[] = $parent->menu_name_ru;
 			}
 		}
 		$path[] = $element['menu_name_ru'];

		$sel_p = array();
		$tree = $this->tree->getAllNodes(true);
		$j = 0;
		foreach ( $tree as $val)
		{
			if($element['site'] == $val['site'])
			{
    			$sel_p[$j]['id'] = $val['id'];
    			$sel_p[$j]['name'] = str_repeat("&nbsp; &nbsp;",$val['level']-1).$val['menu_name_ru'];
    			$j++;
			}
		}

    	$form = new Llib_Form($this->_request);

        if ($this->_request->isPost()) {
        	$data = $form->GetPostedData();
			$this->tree->moveTree($id, $data['struct'], $data['type'], $copy = false);
			$this->_redirect('/'.$this->controller.'#'.$id);
        }

        $d['struct'] = $sel_p;
        $d['type']  = array(
    				array('id' => NESE_MOVE_AFTER, 'name' => 'Вставить после'),
    				array('id' => NESE_MOVE_BEFORE, 'name' => 'Вставить перед'),
    				array('id' => NESE_MOVE_BELOW, 'name' => 'Подменю')
					);

		$form->AddData($d);

    	$this->startContent();
	        $this->view->xmlWriter->startElement("Main");
	        $this->view->xmlWriter->writeAttribute('id', $id);
	        $this->view->assign('Title', 'Переместить');
	        $this->view->assign($form->GetFrom());
		    $this->view->xmlWriter->endElement();
	    $this->view->xmlWriter->endElement();
    }

    public function GetTypeList($a = null, $path)
    {

    	$data = array(
    				array('id' => NESE_MOVE_AFTER, 'name' => 'Вставить после (\\'.implode('\\', $path).')'),
    				array('id' => NESE_MOVE_BEFORE, 'name' => 'Вставить перед (\\'.implode('\\', $path).')'),
    				array('id' => NESE_MOVE_BELOW, 'name' => 'Подменю (\\'.implode('\\', $path).')')
					);

    	if(count($data) > 0 && !is_null($a))
    	foreach($data as $k => $v)
    	  	if($v['id'] == $a) $data[$k]['__attributes']['active'] = 1;

    	return $data;
    }

    public function gettypelistqAction()
    {
		$id  = intval($_REQUEST['id']);
		if(!($id > 0)) return '';

		$element = $this->tree->pickNode($id, true);
		$parents = $this->tree->getParents($id);
 		$path = array();
 		if (sizeof($parents)) {
 			foreach($parents as $parent) {
					$path[] = $parent->menu_name_ru;
 			}
 		}
 		$path[] = $element['menu_name_ru'];

		echo '<option value="' . NESE_MOVE_AFTER. '">Вставить после (\\'.implode('\\', $path).')</option>';
		echo '<option value="' . NESE_MOVE_BEFORE. '">Вставить до (\\'.implode('\\', $path).')</option>';
		echo '<option value="' . NESE_MOVE_BELOW. '">Подменю (\\'.implode('\\', $path).')</option>';

    	die();
    }

    public function ajaxRoleListAction()
    {
    	$a  = $_REQUEST['a'];

    	$data = $this->table_roles->GetRolesList($a);
    	foreach ($data as $k => $v)
    	{
    		echo  '<option value="'.$v['id'].'">'.$v['name_full'].'</option>';
    	}

    	die();
    }

    public function addroleAction()
    {
    	$data['role_id'] = $this->_request->getParam('id_role');
    	$data['resource_id'] = $this->_request->getParam('id_res');
    	$this->table_rules->insert($data, $this->_user->id);

    	die();
    }

    public function removeroleAction()
    {
    	$data['role_id'] = $this->_request->getParam('id_role');
    	$data['resource_id'] = $this->_request->getParam('id_res');
    	$this->table_rules->remove($data);

    	die();
    }

    public function applyruleAction()
    {
    	$allow = trim($this->_request->getParam('allow'));
    	$deny = trim($this->_request->getParam('deny'));
    	$resource_id = $this->_request->getParam('resource_id');
    	$role_id = $this->_request->getParam('role_id');

    	if($allow != '') $params['allow'] = explode(';', $allow);
    	if($deny != '') $params['deny'] = explode(';', $deny);


    	/*$fp = fopen($this->_files_path.'/a.txt', 'w+');
    	fwrite($fp, 'allow:'.$allow.'; deny:'.$deny);
    	fclose($fp);
    	die();*/

    	$this->table_rules->update($params, $resource_id, $role_id, $this->_user->id);

    	die();
    }

    public function getruleAction()
    {
    	$role_id  = $_REQUEST['id_role'];
    	$resource_id   = $_REQUEST['id_res'];

    	if(!($role_id > 0)) return '';
    	if(!($resource_id > 0)) return '';

    	$rules = $this->table_rules->GetRuleByRoleRes($role_id, $resource_id);

    	foreach($rules as $k => $rule)
    	{
    		$privs = $this->table_rules->GetPrivByRule($rule['id']);
    		if(count($privs) == 0)
    		{
    			$chk_rules[] = 'rules_all_'.$rule['type'];
    		}
    		else
    		   foreach($privs as $priv_item)
    		   {
    		   	   $chk_rules[] = 'rules_'.$priv_item['name'].'_'.$rule['type'];
    		   }
    	}

    	/*$fp = fopen($this->_files_path.'/a.txt', 'w+');
    	fwrite($fp, count($rules));
    	fclose($fp);*/


		echo Zend_Json::encode($chk_rules);

    	die();
    }

    // *****************************
    // PHOTO



    public function photosAction()
    {
    	$id = $this->_request->getParam('id');
    	if(!($id > 0)) $this->_redirect('/error/e404');

    	$form = new Llib_Form($this->_request);

    	if ($this->_request->isPost())
    	{
    		$d = $form->GetPostedData();
    		$this->table_objects->order_dragsort($d['list1SortOrder']);
    	}

    	$this->startContent();
	        $this->view->xmlWriter->startElement("Main");
	        $this->view->xmlWriter->writeAttribute('id', $id);
	        $this->view->xmlWriter->writeAttribute('table_name', 'objects');
			$this->view->assign($form->GetFrom());
	        $this->view->assign('photos', $this->table_objects->GetDataParamsList(array('id_cat' => $id)));
		    $this->view->xmlWriter->endElement();
	    $this->view->xmlWriter->endElement();
    }

    public function addphotoAction()
    {
    	$article_id = $this->_request->getParam('id');
    	if(!($article_id > 0)) $this->_redirect('/error/e404');

    	$d['id_cat'] = $article_id;

		$id = $this->table_objects->insert($d, $this->_user->id);

		if($id > 0)
		{
			$this->_redirect('/'.$this->controller.'/editphoto/id/'.$id);
		}else $this->_redirect('/error/e404');
    }

	public function editphotoAction()
    {
    	$id = $this->_request->getParam('id');
    	if(!($id > 0)) $this->_redirect('/error/e404');

    	$data = $this->table_objects->GetDataRow($id);
    	$cat = $this->_table->GetDataRow($data['id_cat']);

    	$form = new Llib_Form($this->_request);

        if ($this->_request->isPost())
        {
			$d = $form->GetPostedData();

			$this->LoadAvatar($id, $form, $d, 'objects');

        	if($this->table_objects->update($d, $id, $this->_user->id)) $form->SetSuccess();
        	else $form->SetError($this->_table->GetError());
        }

        $data = $this->table_objects->GetDataRow($id);

        $form->AddData($data);

    	$this->startContent();
	        $this->view->xmlWriter->startElement("Main");
	        $this->view->xmlWriter->writeAttribute('id', $cat['id']);
	        $this->view->xmlWriter->writeAttribute('title', $cat['title_ru']);
	        $this->view->assign($form->GetFrom());
		    $this->view->xmlWriter->endElement();
	    $this->view->xmlWriter->endElement();
    }


    public function ajaxAddPrivAction()
    {
        $this->table_privilege = new Admin_Table_Privilege();

        $d['id_cat'] = $this->_getParam('id');
        $d['name'] = $this->_getParam('name');
        $d['name_full'] = $this->_getParam('name_full');

        $id = $this->table_privilege->insert($d, $this->_user->id);

        die($id);
    }

    public function ajaxRemovePrivAction()
    {
        $this->table_privilege = new Admin_Table_Privilege();

        $id = $this->_getParam('id');
        $this->table_privilege->remove($id);

        die('OK');
    }

    public function refreshIdtAction()
    {
        $id = $this->_getParam('id');
        $d['menu_name_ru'] = $this->_getParam('title');
        $d['idt'] = $this->tstring($d['menu_name_ru']);

        $this->_table->update_all($d, $id);


		echo $d['idt'];

        die();
    }

    public function refreshUrlAction()
    {
        $id = $this->_getParam('id');
        $idt = $this->_getParam('idt');
        $childs = $this->_getParam('childs', 0);

		$this->refreshUrl($id, $idt, $childs);

		$cat = $this->_table->GetDataRow($id);
		echo $cat['url'];

        die();
    }

	public function  refreshUrl($id, $idt, $is_childs = false)
	{
		$cat = $this->_table->GetDataRow($id);
		$parent = $this->_table->GetDataRow($cat['parent_id']);

		$d['url'] =  ($parent['url'] == '/' ? '' : $parent['url']).'/'.$idt;
		$d['idt'] = $idt;
		$this->_table->update_all($d, $id);

		if($is_childs)
		{
			 $childs = $this->_table->GetChildList($id);
			 if(count($childs) > 0)
			 foreach($childs as $k => $v)
					$this->refreshUrl($v['id'], $v['idt'], $is_childs);
		}
	}


}
